package com.cyj.dream.auth.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cyj.dream.auth.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

/**
 * @Description: 身份验证失败处理程序
 * @BelongsProject: DreamChardonnay
 * @BelongsPackage: com.cyj.dream.auth.handler
 * @Author: ChenYongJia
 * @CreateTime: 2021-09-30 14:20
 * @Email: chen87647213@163.com
 * @Version: 1.0
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    /**
     * 登录失败返回结果
     *
     * @Author ChenYongJia
     * @CreateTime 2020-11-19 10:45:05
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            log.info("============【登录失败】============>", exception.getMessage());
            ResultUtil.responseJson(response, ResultUtil.resultCode(500, "用户名不存在！"));
        }
        if (exception instanceof LockedException) {
            log.info("============【登录失败】============>", exception.getMessage());
            ResultUtil.responseJson(response, ResultUtil.resultCode(500, "用户被锁定，请联系管理员！"));
        }
        if (exception instanceof BadCredentialsException) {
            log.info("============【登录失败】============>", exception.getMessage());
            ResultUtil.responseJson(response, ResultUtil.resultCode(500, "用户名密码不正确"));
        }
        ResultUtil.responseJson(response, ResultUtil.resultCode(500, "登录失败"));
    }

}
